#include "input.h"
#include "OgreStringConverter.h"
#include "pong3d.h"
#include <iostream>

using namespace std;

InputHandler::InputHandler(Ogre::RenderWindow *window)
{
	unsigned long hWnd;
	OIS::ParamList pl;
	std::ostringstream windowHndStr;

	window->getCustomAttribute("WINDOW", &hWnd);
	windowHndStr << hWnd;
	pl.insert(std::make_pair(std::string("WINDOW"), windowHndStr.str()));

#if defined OIS_LINUX_PLATFORM
	pl.insert(std::make_pair(std::string("x11_mouse_grab"), std::string("false")));
	pl.insert(std::make_pair(std::string("x11_mouse_hide"), std::string("false")));
	pl.insert(std::make_pair(std::string("x11_keyboard_grab"), std::string("false")));
	pl.insert(std::make_pair(std::string("XAutoRepeatOn"), std::string("true")));
#endif

	m_ois = OIS::InputManager::createInputSystem(pl);
	mPong3D = &Pong3D::getSingleton();

	mMouse = static_cast<OIS::Mouse*>(m_ois->createInputObject( OIS::OISMouse, true ));
	mKeyboard = static_cast<OIS::Keyboard*>(m_ois->createInputObject( OIS::OISKeyboard, true ));
	try {
		mJoy = static_cast<OIS::JoyStick*>(m_ois->createInputObject( OIS::OISJoyStick, true ));
		mJoy->setEventCallback(this);
	}
	catch(...) {
		mJoy = 0;
	}

	mMouse->setEventCallback(this);
	mKeyboard->setEventCallback(this);
}

InputHandler::~InputHandler() {
	if (mMouse)
		m_ois->destroyInputObject(mMouse);
	if (mKeyboard)
		m_ois->destroyInputObject(mKeyboard);
	if (mJoy)
		m_ois->destroyInputObject(mJoy);

	OIS::InputManager::destroyInputSystem(m_ois);
}

void InputHandler::capture() {
	if(mMouse)
		mMouse->capture();
	
	if(mKeyboard)
	mKeyboard->capture();
	
	if(mJoy)
		mJoy->capture();
}

void  InputHandler::setWindowExtents(int width, int height)
{
	//Set Mouse Region.. if window resizes, we should alter this to reflect as well
	const OIS::MouseState &ms = mMouse->getMouseState();
	ms.width = width;
	ms.height = height;
}

// MouseListener
bool InputHandler::mouseMoved(const OIS::MouseEvent &evt) {
	return true;
}

bool InputHandler::mousePressed(const OIS::MouseEvent &evt, OIS::MouseButtonID btn) {
	return true;
}

bool InputHandler::mouseReleased(const OIS::MouseEvent &evt, OIS::MouseButtonID btn) {
	return true;
}


// KeyListener
bool InputHandler::keyPressed(const OIS::KeyEvent &evt) {
	mPong3D->doAction(evt);
	return true;
}

bool InputHandler::keyReleased(const OIS::KeyEvent &evt) {
	
	return true;
}


// JoyStickListener
bool InputHandler::buttonPressed(const OIS::JoyStickEvent &evt, int index) {
	return true;
}

bool InputHandler::buttonReleased(const OIS::JoyStickEvent &evt, int index) {
	return true;
}

bool InputHandler::axisMoved(const OIS::JoyStickEvent &evt, int index) {
	return true;
}

bool InputHandler::povMoved(const OIS::JoyStickEvent &evt, int index) {
	return true;
}

